package com.ca.ridersclubapplication.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.AccountActivity;
import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.LongEntity;
import com.ca.ridersclubapplication.request.AccountRequester;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.dto.AccountCardDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.ImageUtils;

import java.util.ArrayList;
import java.util.List;

public class AccountAdapter extends RecyclerView.Adapter<AccountAdapter.AccountHolder> {

    private final Activity activity;
    private List<AccountCardDto> list;

    public AccountAdapter(Activity activity, List<AccountCardDto> list) {
        this.activity = activity;
        this.list = list == null ? new ArrayList<>() : list;
    }

    @NonNull
    @Override
    public AccountHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.account_item_layout, parent, false);
        return new AccountHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AccountHolder holder, int position) {

        AccountCardDto dto = list.get(position);
        ImageUtils.loadCircleImage(activity, FileRequester.HEADER_BY_ID_BASE_URL + dto.getAccountId(), holder.headerView);
        holder.nameView.setText(dto.getNickname());
        holder.profileView.setText(dto.getProfile());

        Long loginId = DataHandler.getToken(activity).getId();
        if (!dto.getAccountId().equals(loginId)) {
            //  请求用户是否关注
            AccountRequester.isFollow(activity, dto.getAccountId(), new AfterExecutor<Boolean>() {
                @Override
                public void execute(Result<Boolean> result) {
                    Boolean isFollow = result.getData();
                    if (result.isSuccess() && isFollow) {
                        holder.followButton.setBackgroundColor(activity.getResources().getColor(R.color.page_second_background));
                        holder.followButton.setTextColor(activity.getResources().getColor(R.color.secondary_text));
                        holder.followButton.setText("取关");
                        holder.isFollow = true;
                    } else {
                        holder.followButton.setBackgroundColor(activity.getResources().getColor(R.color.primary));
                        holder.followButton.setTextColor(activity.getResources().getColor(R.color.white_text));
                        holder.followButton.setText("关注");
                        holder.isFollow = false;
                    }
                }
            });

            //  设置监听事件
            holder.followButton.setOnClickListener(v -> {
                if (holder.isFollow) {
                    AccountRequester.deleteFollow(activity, dto.getAccountId(), new AfterExecutor<String>() {
                        @Override
                        public void execute(Result<String> result) {
                            if (result.isSuccess()) {
                                //  取关成功
                                holder.isFollow = false;
                                holder.followButton.setBackgroundColor(activity.getResources().getColor(R.color.primary));
                                holder.followButton.setTextColor(activity.getResources().getColor(R.color.white_text));
                                holder.followButton.setText("关注");

                                //  放入数据，触发回调视图更新
                                DataHandler.putData(new LongEntity("FollowCount:" + loginId, -1L));
                            }
                        }
                    });
                } else {
                    AccountRequester.addFollow(activity, dto.getAccountId(), new AfterExecutor<String>() {
                        @Override
                        public void execute(Result<String> result) {
                            if (result.isSuccess()) {
                                //  关注成功
                                holder.isFollow = true;
                                holder.followButton.setBackgroundColor(activity.getResources().getColor(R.color.page_second_background));
                                holder.followButton.setTextColor(activity.getResources().getColor(R.color.secondary_text));
                                holder.followButton.setText("取关");

                                //  放入数据，触发回调视图更新
                                DataHandler.putData(new LongEntity("FollowCount:" + loginId, 1L));
                            }
                        }
                    });
                }
            });
        }
        else {
            holder.followButton.setVisibility(View.GONE);
        }

        holder.parent.setOnClickListener(v -> {
            Intent intent = new Intent(activity, AccountActivity.class);
            intent.putExtra("accountId", dto.getAccountId());
            activity.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setList(List<AccountCardDto> list) {
        if (list == null) {
            list = new ArrayList<>();
        }

        if (!this.list.equals(list)) {
            this.list = list;
            notifyDataSetChanged();
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    public void appendListToBottom(List<AccountCardDto> list) {

        if (list == null) {
            return;
        }

        this.list.addAll(list);
        notifyDataSetChanged();
    }

    public static class AccountHolder extends RecyclerView.ViewHolder {

        public boolean isFollow;
        public ConstraintLayout parent;
        public ImageView headerView;
        public TextView nameView;
        public TextView profileView;
        public Button followButton;

        public AccountHolder(@NonNull View itemView) {
            super(itemView);

            parent = itemView.findViewById(R.id.cl_parent);
            headerView = itemView.findViewById(R.id.iv_header);
            nameView = itemView.findViewById(R.id.tv_name);
            profileView = itemView.findViewById(R.id.tv_profile);
            followButton = itemView.findViewById(R.id.btn_follow);
        }
    }
}
